package com.bjpower.springboot.preparedstatement.crud;

import org.junit.Test;

import com.bjpower.springboot.util.JDBCUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 * @Author: yg
 * @create 2025-01-23 - 21:42
 * @
 */
public class PreparedStatementUpdateTest {
    @Test
    public void testInsert() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Connection conn = null;
        PreparedStatement ppst = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "insert into account(username, balance) values(?,?)";//?占位符
            ppst = conn.prepareStatement(sql);
            //5.填充占位符
            ppst.setString(1, "梅.帕克");
            ppst.setString(2, "3000");
            ppst.execute();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ppst);
        }
    }
    @Test
    public void update(String sql, Object ...args) throws Exception {
        Connection conn = null;
        PreparedStatement ppst = null;
        try {
            conn = JDBCUtils.getConnection();
            //2.获取sql语句并生成实例
            ppst = conn.prepareStatement(sql);
            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                ppst.setObject(i+1, args[i]);
            }
            //4.执行
            ppst.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeResource(conn, ppst);
        }
    }

    @Test
    public void testUpdate() throws Exception {
        Connection conn = null;
        PreparedStatement ppst = null;
        try {
            //1.创建数据库连接
            conn = JDBCUtils.getConnection();
            //2.获取sql语句并生成实例
            String sql = "update account set username = ? where id = ?";
            ppst = conn.prepareStatement(sql);
            //3.填充占位符
            ppst.setString(1, "阿宝");
            ppst.setInt(2, 1);
            //4.执行
            ppst.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            //5.资源关闭
            JDBCUtils.closeResource(conn, ppst);
        }
    }
}
